#pragma once

#include "Socket.hpp"
#include "Connection.hpp"
#include <memory>
#include"Reactor.hpp"

using namespace hcc;
class Listener
{
public:
    Listener(uint16_t port) : _port(port),_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(port);
        if (_listensock->Sockfd() < 0)
        {
            LOG(FATAL, "sockfd create error!\n");
        }
        LOG(INFO, "sockfd create success !\n");
    }
    int ListenSockfd()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection *conn)
    {
        while (true)
        {
            errno = 0;
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr, &code);
            if (sockfd > 0)
            {
                LOG(INFO, "获得新连接,ip:%s , port: %d ,fd: %d", addr.Ip().c_str(),addr.Port(),sockfd);
                conn->_R->AddConnection(sockfd,EPOLLIN|EPOLLET,addr,NormalConnection);
                break;
            }
            else
            {

                if (code == EWOULDBLOCK)
                {
                    LOG(INFO, "底层连接全部获取完毕 \n");
                    break;
                }
                else if (code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "获取连接失败 !\n");
                    break;
                }
            }
        }
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};